<template>
  <div class="container">
    <div class="bigbox">
      <div class="twobox">
        <!-- 密码登录、验证码登录 -->
        <div class="cont">
          <!-- 标题 -->
          <p>
            <span v-show="popupState!=3" :class="{'active':popupState===1}" @click="tabChange(1)">密码登录</span>
            <span v-show="popupState!=3" :class="{'active':popupState===2}" @click="tabChange(2)">验证码登录</span>
            <span v-show="popupState===3" :class="{'active':popupState===3}">找回密码</span>
          </p>
          <div class="cont-form" :class="{'popupState3':popupState===3}">
            <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="0px" class="ms-content">
              <!-- 输入框 -->
              <el-form-item prop="username">
                  <el-input v-model="loginForm.username" placeholder="手机号/工号">
                      <template #prepend>
                        <i class="el-icon-user"></i>
                      </template>
                  </el-input>
              </el-form-item>
              <el-form-item v-if="popupState!=2" prop="password">
                  <el-input type="password" v-model="loginForm.password" :placeholder="popupState===1?'密码':'设置密码'" show-password>
                      <template #prepend>
                        <i class="el-icon-lock"></i>
                      </template>
                  </el-input>
              </el-form-item>
              <el-form-item v-if="popupState!=1" prop="code">
                  <el-input v-model="loginForm.code" placeholder="验证码" @keyup.enter="submitForm()">
                      <template #prepend>
                        <i class="el-icon-circle-check"></i>
                      </template>
                      <template slot="append">
                        <div class="get-code">
                          <div class="state1" v-if="state === 1" @click="getCode">发送验证码</div>
                          <div class="state2" v-if="state === 2">{{ codeNum }}秒后重发</div>
                          <div class="state3" v-if="state === 3" @click="getCode">重新发送</div>
                        </div>
                      </template>
                  </el-input>
              </el-form-item>
              <!-- 记住密码 忘记密码 -->
              <div class="tab" v-if="popupState===1">
                <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">记住密码</el-checkbox>
                <span @click="retrievepsdOpen()">忘记密码？</span>
              </div>
              <div class="tab" v-if="popupState===2"></div>
              <div class="tab" v-if="popupState===3" style="height:30px;">
                <span></span>
                <span @click="psdOpen()">密码登录</span>
              </div>
              <!-- 按钮 -->
              <div class="login-btn" v-if="popupState!=3">
                <el-button
                  :loading="loading"
                  size="medium"
                  type="primary"
                  style="width: 100%"
                  @click.native.prevent="submitForm"
                >
                  <span style="letter-space: 2px" v-if="!loading">登录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
              </div>
              <div class="login-btn" v-if="popupState===3">
                <el-button
                  :loading="loading"
                  size="medium"
                  type="primary"
                  style="width: 100%"
                  @click.native.prevent="resetPassword"
                >
                  <span style="letter-space: 2px">完成</span>
                </el-button>
              </div>
            </el-form>
          </div>
          
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { getCode } from '@/api/login'

export default {
  name: "login",
  data() {
    return {
      popupState: 1,  //1密码登录 2验证码登录 3找回密码
      loading: false,
      loginForm: {
        username: "",
        password: "",
        code: "",
        rememberMe: false
      },
      rules: {
        username: [
          { required: true, trigger: "blur", message: "手机号/工号不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        code: [
          { required: true, trigger: "blur", message: "验证码不能为空" },
        ],
        /* code: [
          { validator: validateCode, trigger: 'blur' }
        ], */
      },
      state: 1, //获取验证码状态
      codeNum: 60, //验证码剩余时间
      msgCheck: '', //短信验证码 写死（有特权的人可直接进）
    };
  },
  created() {
    this.getCookie();
  },
  mounted() {},
  methods: {
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    // 获取验证码
    getCode() {
      let validateList = [];
      this.$refs["loginForm"].validateField(['username'],(error) => {
        validateList.push(error)
      })
      if(validateList.every(item => item===''))  {
        var that = this;
        this.state = 2;
        this.codeNum = 60;
        let interval = window.setInterval(function () {
          if (that.codeNum-- <= 0) {
            that.codeNum = 60;
            that.state = 3;
            window.clearInterval(interval);
          }
        }, 1000);

        // 后台交互 发送验证码 this.loginForm.password
        getCode(this.loginForm.username).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "验证码已成功发送至您的手机，请注意查收!",
              type: "success",
              center: true,
            });
          }
        });
      }
    },
    // 登录提交
    submitForm() {
      // validate 传入一个回调函数，回调函数有两个参数。分别是：是否校验成功、未通过校验的字段 
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          /**
           * 如果验证码有值，并且验证码值为定死的值（1111）  放行，通过
           * 如果验证码有值，并且值不等于定死的值  返回'请先获取验证码！'
           */
          // if (this.state===1 && this.loginForm.code!=this.msgCheck) return this.msgError('请先获取验证码!')
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30,});
            Cookies.set("rememberMe", this.loginForm.rememberMe, { expires: 30,});
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              Cookies.set("isLogin", true)
              // Cookies.set("userInfo", JSON.stringify(res.result))
              this.$store.commit("handleCollapse", false);
              this.$store.commit("clearTags");
              this.$router.push({ path: "/" });
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    // 找回密码 - 提交
    resetPassword() {
      this.$refs.loginForm.validate((valid) => {
        let _this = this;
        if (valid) {
          console.log('this.loginForm.code',this.loginForm.code)
          console.log('this.msgCheck',this.msgCheck)
          // if (this.state===1 && this.loginForm.code!=this.msgCheck) return this.msgError('请先获取验证码！')
          this.$store
            .dispatch("RepairPassword", this.loginForm)
            .then(() => {
              this.$confirm('修改密码成功，请重新登录!', "提示", {
                confirmButtonText: "确定"
              }).then(function() {
                _this.resetForm();
                _this.popupState = 1;
              })
            })
            .catch((error) => {
              this.resetForm() 
            });
          }
      });
    },
    // 切换 密码登录、验证码登录
    tabChange(val) {
      this.resetForm();
      this.popupState = val
    },
    // 找回密码 - 打开弹框
    retrievepsdOpen() {
      this.resetForm();
      this.popupState = 3;
    },
    // 密码登录 - 打开弹框
    psdOpen() {
      this.resetForm();
      this.popupState = 1;
    },
    resetForm() {
      this.loginForm = {
        username: "",
        password: "",
        code: ""
      }
      this.state = 1;
      // this.msgCheck = "";
      this.codeNum = 60;
      Cookies.remove("username");
      Cookies.remove("password");
      Cookies.remove("rememberMe");
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-input-group__prepend {
  padding: 0 10px;
  background: #f4f4f4;
  img {
    width: 16px;
    height: 16px;
  }
}
.container {
  width: 100%;
  height: 100%;
  background: url(../assets/img/login-bg.jpg) no-repeat;
  background-position: center;
  background-size: 100%;
  position: fixed;
}
.bigbox {
  width: 400px;
  height: 430px;
  background: rgba(255, 255, 255, 0.3);
  position: relative;
  top: 50%;
  margin-top: -223px;
  left: 60%;
  display: flex;
  align-items: center;
  justify-content: center;
  .twobox {
    width: 94%;
    height: 94%;
    background: #fff;
    position: relative;
    .cont {
      width: 298px;
      height: 320px;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      p {
        font-size: 18px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e5e5e5;
        span {
          padding-bottom: 8px;
          margin-right: 20px;
          cursor: pointer;
        }
        span.active {
          border-bottom: 2px solid blue;
        }
      }
      .cont-form {
        padding-top: 54px;

        .get-code {
          cursor: pointer;
        }
        .get-code .state2 {
          cursor: text;
        }
        .tab {
          width: 100%;
          display: flex;
          justify-content: space-between;
          height: 44px;
        }
        .tab span {
          color: #606266;
          cursor: pointer;
        }
      }
      .cont-form.popupState3 {
        padding-top: 30px;
      }

      ::v-deep .el-input__inner {
        background: #f4f4f4;
      }
      .el-button {
        width: 100%;
        font-size: 17px;
        margin-top: 1vh;
      }
      font {
        margin-left: 4vh;
      }
    }
  }
}
</style>